<?php
// include the file for the database connection
include_once("database.php");
header("Content-type: text/xml");

//Create database interface
$db	= new database();

//Do a query to find out how many rows in table
$sql	= "select count(*) as numberRows from shoe_specialOffers, brand where shoe_specialOffers.brandID = brand.brandID";
$result	= $db->getResult($sql);
$maxNumber	= (int) $result[0]['numberRows'];

// generate a random number between 1 and the maximum rows in the table
$number = rand(1, $maxNumber);


// if useXML was sent as part of the url then
if (isset( $_REQUEST['useXML'] )) {
    // echo whatever getXMLOffer returns to the browser or back to the ajax script
    echo getXMLOffer($number);

} else {    // otherwise just an html record is required

    // so echo whatever getHTMLOffer returns to the browser or back to the ajax script
    echo getHTMLOffer($number);
}

function getHTMLOffer($number) {
    // store the sql for a special offer with the id matching the random number and wrap things using concat in an html 'wrapper'
    $sql = "select concat('<p>&#8220;',shoeName,'&#8221;<br />\n<span class=\"brand\">Brand: ',brandName,'</span><br />\n<span class=\"price\">Price: ',price,'</span></p>') as offer from shoe_specialOffers, brand where shoeID=$number AND shoe_specialOffers.brandID = brand.brandID";

    // get the one quotation returned
    $db	= new database();
    $offer = $db->getResult($sql);
    // return the quote
    return $offer[0]['offer'];

}

function getXMLOffer($number) {
    $sql = "select shoeID, shoeName, brandName, price from shoe_specialOffers, brand where shoeID=$number AND shoe_specialOffers.brandID = brand.brandID";
    $db	= new database();
    $xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
    $rsOffer = $db->getQuery($sql);
    // start to assemble an output string with the xml head and root element
    $output = $xmlHeader;
    $output .= "<root>\n";
    while ( $record = mysql_fetch_assoc( $rsOffer ) ) {
        // start a new record element in xml and add to the output
        $output .= "\t<offer>\n";
        // iterate through each record pulling out the fieldname and its value
        foreach ( $record as $field => $value ) {
            $value = htmlspecialchars( $value );
            // wrap up the fields and values as xml
            $output .= "\t\t<$field>$value</$field>\n";
        }
        $output .= "\t</offer>\n";
    }
    $output .= "</root>";
    return $output;
}
?>